﻿using Company.Database.Entities;
using Microsoft.EntityFrameworkCore;

namespace Company.Database.Sqlite
{
    public class AlarmRepository : RepositoryBase, IAlarmRepository
    {
        public bool Delete(AlarmEntity entity)
        {
            db.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
            return db.SaveChanges() > 0;
        }

        public List<AlarmEntity> GetAll()
        {
            return [.. db.Alarms];
        }

        public bool Insert(AlarmEntity entity)
        {
            try
            {
                // 确保新插入的实体 Id 为 0，让数据库自动生成主键
                entity.Id = 0;
                
                // 同时确保 InsertDate 是当前时间
                entity.InsertDate = DateTime.Now;
                
                db.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added;
                var result = db.SaveChanges() > 0;
                
                System.Diagnostics.Debug.WriteLine($"成功插入报警记录: ID={entity.Id}, 房间={entity.RoomNumber}, 地址={entity.AddressNumber}");
                
                return result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"插入报警记录失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"实体信息: Id={entity.Id}, RoomNumber={entity.RoomNumber}, AddressNumber={entity.AddressNumber}");
                
                // 可以选择返回 false 而不是抛出异常，让调用者继续执行
                return false;
            }
        }

        public bool Update(AlarmEntity entity)
        {
            try
            {
                db.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                return db.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新报警记录失败: {ex.Message}");
                return false;
            }
        }
    }
}
